<?php


namespace WechatPayment\tools;


class Request
{
    /**
     * curl 请求
     * @param $url
     * @param bool $post
     * @param null $data
     * @param bool $json
     * @param string $Authorization
     * @param array $needpath
     * @return array|mixed
     */
    function curl_request($url, $post = false, $data = NULL, $json = true, $Authorization = '')
    {
        $curl = curl_init();
        if ($post == "GET") {
            $url = $url . "?" . http_build_query($data);
        }

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

        // 设置请求头
        $header = [
            'Accept: application/json',
            'Content-type: application/json',
            !empty($Authorization) ? $Authorization : ''
        ];

        if (!empty($data)) {
            if ($json && is_array($data)) {
                $data = json_encode($data);
            }
            if ($post == 'POST') {
                array_push($header, "Content-Length:" . strlen($data));
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            } else {
                curl_setopt($curl, CURLOPT_POST, 0);
            }
            curl_setopt($curl, CURLOPT_HEADER, 0);
            curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36');
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return array('errorno' => false, 'errmsg' => $errorno);
        }
        curl_close($curl);
        return json_decode($res, true);
    }
}